package cn.edu.buu.hospital.web;
import cn.edu.buu.hospital.entity.Department;
import cn.edu.buu.hospital.entity.Hospital;
import cn.edu.buu.hospital.entity.User;
import cn.edu.buu.hospital.entity.Doctor;
import cn.edu.buu.hospital.service.AppointmentService;
import cn.edu.buu.hospital.service.DepartmentService;
import cn.edu.buu.hospital.service.DoctorService;
import cn.edu.buu.hospital.service.HospitalService;
import cn.edu.buu.hospital.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class AdminLoginOutController {
    @Autowired
    private UserService userService;
    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private AppointmentService appointmentService;
    @Autowired
    private DoctorService doctorService;

    //退出:结束会话HttpSession,让会话失效
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:toAdminLogin";
    }

    @PostMapping("/adminLogin")
    //用户执行登录
    public String adminLogin(@RequestParam("userName") String userName,
                             @RequestParam("userPassword") String userPassword,
                             @RequestParam("userType") Integer userType,
                             HttpSession session) {
        User loginAdmin = userService.findAdmin(userName, userPassword, userType);
        if(loginAdmin==null){
            //用户名或密码错误，去往登录页,跳转：重定向redirct
            return "redirect:toAdminLogin?flag=-1";
        }
        
        // 如果用户没有设置头像，设置默认头像
        if (loginAdmin.getHeadpic() == null || loginAdmin.getHeadpic().isEmpty()) {
            loginAdmin.setHeadpic("admin.png");
        }
        //登录成功,记住用户，把loginAdmin放入HttpSession作用域中
        session.setAttribute("loginAdmin",loginAdmin);
        
        // 根据用户类型跳转到不同页面
        // 患者用户(type=1)直接跳转到预约记录管理
        if (loginAdmin.getType() != null && (loginAdmin.getType() == 1 )) {
            return "redirect:/appointment/find";
        }
        // 其他用户(管理员)跳转到控制面板
        return "redirect:/toWorkspace";
    }
    //去往管理员的登录页
    @GetMapping("/toAdminLogin")
    public String toAdminLogin(){
        //跳转：转发
        return "backend/login";
    }
    @RequestMapping("/toWorkspace")
    //model是数据模型
    public String toWorkspace(Model model, HttpSession session) {
        // 权限检查：只有管理员(type=3)可以访问控制面板
        User loginUser = (User) session.getAttribute("loginAdmin");
        if (loginUser == null || loginUser.getType() != 3) {
            // 非管理员用户重定向到预约记录管理页面
            return "redirect:/appointment/find";
        }
        // 1. 查询最新5个科室（传递给页面"最新科室"区域）
        List<Department> departmentList = departmentService.findTopNum(5);
        // 手动为每个科室填充医院信息
        if (departmentList != null && !departmentList.isEmpty()) {
            for (Department department : departmentList) {
                if (department != null && department.getHospitalid() != null) {
                    try {
                        Hospital hospital = hospitalService.findById(department.getHospitalid());
                        if (hospital != null) {
                            department.setHospital(hospital);
                        }
                    } catch (Exception e) {
                        // 处理获取医院信息时的异常，不影响科室数据的返回
                        System.err.println("获取医院信息失败: " + e.getMessage());
                    }
                }
            }
        }
        model.addAttribute("departmentList", departmentList);

        // 2. 查询所有医院
        List<Hospital> hospitalList = hospitalService.findAll();
        model.addAttribute("hospitalList", hospitalList);
        
        // 3. 统计数据
        // 科室总数
        long deptTotal = departmentService.findTotal();
        model.addAttribute("total", deptTotal);
        
        // 医院总数
        long hospitalCount = hospitalList != null ? hospitalList.size() : 0;
        model.addAttribute("hospitalCount", hospitalCount);
        
        // 医生总数 - 从Doctor表获取真实医生数量
        List<Doctor> doctorList = doctorService.findAll();
        long doctorCount = doctorList != null ? doctorList.size() : 0;
        model.addAttribute("doctorCount", doctorCount);
        
        // 今日预约数 - 使用动态数据
        long todayAppointmentCount = appointmentService.countTodayAppointments();
        model.addAttribute("todayAppointmentCount", todayAppointmentCount);

        return "backend/workspace";
    }
}
